package com.hushao.aimi.common;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @description: 返回消息
 * @author: 胡少
 * @create: 2018-06-03 22:43
 **/
@Slf4j
@Data
public class ServerResponse{
    private int status;
    private String msg;
    private Object data;

    public ServerResponse(int status) {
        this.status = status;
    }

    public ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;

    }

    public ServerResponse(int status, Object data) {
        this.status = status;
        this.data = data;
    }

    public ServerResponse(int status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public static ServerResponse Success(){
        return new ServerResponse(ResponseCode.SUCCESS.getCode());
    }

    public static ServerResponse Success(String msg){
        return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static ServerResponse Success(Object data){
        return new ServerResponse(ResponseCode.SUCCESS.getCode(),data);
    }
    public static ServerResponse Success(String msg,Object data){
        return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg,data);
    }

    public static ServerResponse Error(ResponseCode responseCode){
        return new ServerResponse(responseCode.getCode(),responseCode.getDesc());
    }

    public static ServerResponse Error(String msg){
        return new ServerResponse(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),msg);
    }
    public static ServerResponse Error(int status,String msg){
        return new ServerResponse(status,msg);
    }

    /**
     *  使用response输出JSON
     * @param response
     * @param msg
     */
    public static void out(ServletResponse response, String msg){

        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(out!=null){
                out.flush();
                out.close();
            }
        }
    }

}
